<template>
    <div class="common-layout">
      <el-container>
        <el-header style=" font-size: 15px; background-color:gray;">
            当前登录人：{{counter.userinfo.userName  }}
            <div class="toolbar">
          <el-button style="float:right;" type="danger" :icon="SwitchButton" @click="goout">退出登录</el-button>
        </div>
        </el-header>
        <h4 style="color:darkblue">企业管理 2021-07</h4>
        <el-container>
          <el-aside width="200px">
            <el-menu
        active-text-color="#ffd04b"
        background-color="#545c64"
        class="el-menu-vertical-demo"
        default-active="2"
        text-color="#fff"
        router
        @open="handleOpen"
        @close="handleClose"
      >
        <el-sub-menu index="1">
          <template #title>
            <el-icon><User /></el-icon>
            <span>基础数据</span>
          </template>
          <div v-for="(item,index) in permissionData" :key="index">
            <DynamicMenu :item="item"></DynamicMenu>
          </div>
          <el-menu-item index="/AddnewUser">新增用户</el-menu-item>
          <el-menu-item index="/AddRoleOrPermissions">新增角色</el-menu-item>
          <el-menu-item index="/">测试</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="2">
          <template #title>
            <el-icon><icon-menu /></el-icon>
            <span>溯源管理</span>
          </template>
          <el-menu-item index="/GetTraceablyView"></el-menu-item>
          <el-sub-menu index="3">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>屠宰信息</span>
          </template>
          <el-menu-item index="/GetCultivationList"></el-menu-item>
        </el-sub-menu>
        </el-sub-menu>
      </el-menu>
          </el-aside>
          <el-main>
            <!-- 主要内容 -->
          <div>
            <RouterView></RouterView>
          </div>
          </el-main>
        </el-container>
      </el-container>
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref,onMounted } from 'vue'
import  { ElMessage,ElMessageBox } from 'element-plus'
import axios from 'axios';
import {useRouter} from 'vue-router'
const router=useRouter()
import {useCounterStore} from '@/stores/counter'
const counter=useCounterStore()
import {
  Document,
  Menu as IconMenu,
  Setting,
  User,
  SwitchButton
} from '@element-plus/icons-vue'
import type {RouteRecordRaw} from 'vue-router'
import DynamicMenu from '@/components/DynamicMenu.vue';//导入递归组件
import { UserFilled } from '@element-plus/icons-vue'
//菜单的打开
const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
//菜单的关闭
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}


interface per{
      "permissionId":number,
      "permissionName":string,
      "url":string,
      "routingName":string,
      "component":string,
      "children"?:per[]
}

const permissionData=ref<per[]>([])


onMounted(()=>{
    getper()
})

const getper=()=>{
    axios.get('http://localhost:5072/api/RBAC/TreePermissions')
    .then(async res=>
    {
        console.log(res)
        permissionData.value=res.data.data
        await addDynamicRoutes(permissionData.value)
    })
    .catch(err=>{
        console.log(err)
    })
}
// 动态添加路由的函数
const addDynamicRoutes = async (permissionData: per[]) => {
await permissionData.forEach((permission) => {
    console.log(permission);
    // 创建路由对象
    const route: RouteRecordRaw = {
      path: permission.url,
      name: permission.routingName,//RollBoaAC/Permission
      component: () => import(`../views/RollBoaAC/${permission.component}.vue`),
      children: permission.children
        ? permission.children.map((child) => ({
            path: child.url,
            name: child.routingName,
            component: () => import(`../views/Traceability/${child.component}.vue`),
          })): [], // 如果有子路由，递归生成子路由
    };
    console.log(`../views/${permission.component}.vue`);// 获取当前的路由配置
    const routes = router.options.routes;
    // 找到父路由 MenuView
    const menuViewRoute = routes.find(route => route.name === 'MenuView');
    // 确保 menuViewRoute 存在
    if (menuViewRoute)
     {
        menuViewRoute.children?.push(route); // 使用可选链操作符，确保 children 存在
        console.log(route);
        // 重新添加路由配置
        router.addRoute(menuViewRoute);
     }
     else
     {
       console.error('父路由 MenuView 未找到，无法添加子路由');
     }
      });
      // 重新加载当前路由，确保新路由生效
      router.replace(router.currentRoute.value.path);
      const routes = router.getRoutes();
      console.log(routes);

};

//退出登录
const goout=()=>{
    router.push('/')
}
</script>